#!/bin/bash
# JavaBridge 启动脚本 - 增强版

# 基础配置
BRIDGE_DIR="/www/wwwroot/JavaBridge/WEB-INF/lib"
JAR_PATH="$BRIDGE_DIR/JavaBridge.jar"
JAVA_OPTS="-Xms512m -Xmx1024m -XX:+UseG1GC -Dfile.encoding=UTF-8 -Djava.awt.headless=true"
LOG_DIR="$BRIDGE_DIR/logs_backup"
DAILY_LOG="$LOG_DIR/JavaBridge_$(date +%Y%m%d).log"
PORT=8080
BRIDGE_OPTS="SERVLET:${PORT} 3"

# Java路径（如果检测失败，会自动检测）
JAVA_CMD="/www/server/java/jdk1.8.0_371/bin/java"

# 自动检测Java路径
detect_java() {
    # 调试信息：显示当前PATH
    echo "当前PATH: $PATH" >&2
    
    # 使用which或command命令查找Java路径
    local found_java=$(which java 2>/dev/null || command -v java 2>/dev/null)
    if [ -n "$found_java" ] && [ -f "$found_java" ]; then
        echo "通过which/command找到Java: $found_java" >&2
        echo "$found_java"
        return 0
    fi
    
    # 如果which/command找不到，尝试常见路径
    local common_paths=(
        "/usr/bin/java"
        "/usr/lib/jvm/java-8-openjdk/bin/java"
        "/usr/lib/jvm/java-1.8.0-openjdk/bin/java"
        "/www/server/java/jdk1.8.0_371/bin/java"
        "/www/server/java/jdk8/bin/java"
        "/www/server/java/jdk1.8/bin/java"
        "/opt/jdk1.8.0_371/bin/java"
        "/usr/local/java/bin/java"
        "/usr/lib/jvm/default-java/bin/java"
        "/usr/lib/jvm/java-openjdk/bin/java"
        "/usr/lib/jvm/java-8/bin/java"
        "/usr/lib/jvm/jre-1.8.0/bin/java"
        "/usr/lib/jvm/jre-8/bin/java"
        "/opt/java/bin/java"
        "/usr/local/jdk/bin/java"
    )
    
    for java_path in "${common_paths[@]}"; do
        if [ -f "$java_path" ] && [ -x "$java_path" ]; then
            echo "通过路径扫描找到Java: $java_path" >&2
            echo "$java_path"
            return 0
        fi
    done
    
    echo "未找到Java，请检查Java安装" >&2
    return 1
}

# 路径验证函数
validate_paths() {
    # 进入工作目录
    cd "$BRIDGE_DIR" || {
        echo "错误: 无法进入工作目录: $BRIDGE_DIR"
        exit 1
    }
    
    # 自动检测Java路径
    echo "正在检测Java安装路径..."
    
    # 如果已手动设置JAVA_CMD，优先检测该路径
    if [ -n "$JAVA_CMD" ]; then
        if [ -f "$JAVA_CMD" ] && [ -x "$JAVA_CMD" ]; then
            echo "使用手动设置的Java路径: $JAVA_CMD"
            # 检查Java版本
            local java_version=$($JAVA_CMD -version 2>&1 | head -n1)
            echo "Java版本: $java_version"
        else
            echo "警告: 手动设置的Java路径不存在或不可执行: $JAVA_CMD"
            echo "将尝试自动检测Java路径..."
            # 继续自动检测
            JAVA_CMD=$(detect_java)
        fi
    else
        # 自动检测
        JAVA_CMD=$(detect_java)
    fi
    
    # 最终检测结果
    if [ $? -eq 0 ] && [ -n "$JAVA_CMD" ] && [ -f "$JAVA_CMD" ] && [ -x "$JAVA_CMD" ]; then
        echo "检测到Java: $JAVA_CMD"
        # 检查Java版本
        local java_version=$($JAVA_CMD -version 2>&1 | head -n1)
        echo "Java版本: $java_version"
    else
        echo "错误: 未检测到Java安装"
        echo ""
        echo "1. 手动指定Java路径（推荐）："
        echo "   编辑脚本，取消注释并设置："
        echo "   JAVA_CMD=\"/www/server/java/jdk1.8.0_371/bin/java\""
        echo ""
        echo "2. 检查Java实际安装路径："
        echo "   ls -la /www/server/java/"
        echo "   ls -la /usr/lib/jvm/"
        exit 1
    fi
    
    # 检查JAR文件是否存在
    if [ ! -f "$JAR_PATH" ]; then
        echo "错误: JAR文件不存在: $JAR_PATH"
        echo "请检查JAR文件路径是否正确"
        echo "当前工作目录: $(pwd)"
        echo "尝试查找JAR文件..."
        find /www/wwwroot -name "JavaBridge.jar" -type f 2>/dev/null | head -5
        exit 1
    fi
    
    # 创建日志目录
    if [ ! -d "$LOG_DIR" ]; then
        mkdir -p "$LOG_DIR"
        echo "创建日志目录: $LOG_DIR"
    fi
}

# 检查必要命令是否存在
check_commands() {
    local commands="lsof pgrep pkill"
    for cmd in $commands; do
        if ! command -v $cmd >/dev/null 2>&1; then
            echo "警告: 命令 $cmd 未找到，某些功能可能受限"
        fi
    done
}

# 检查端口占用并清理
check_port() {
    echo "检查端口 ${PORT} 占用情况..."
    
    # 使用lsof检查端口占用
    if command -v lsof >/dev/null 2>&1; then
        PID=$(lsof -ti:${PORT} 2>/dev/null)
        if [ ! -z "$PID" ]; then
            echo "发现端口 ${PORT} 被进程 $PID 占用，正在清理..."
            kill -9 $PID 2>/dev/null
            sleep 2
            # 再次检查确保清理完成
            if lsof -ti:${PORT} >/dev/null 2>&1; then
                echo "警告：端口清理失败，可能影响启动"
            else
                echo "端口清理完成"
            fi
        fi
    else
        # 备用方法：使用netstat检查端口
        echo "lsof命令未找到，使用netstat检查端口..."
        PID=$(netstat -tlnp 2>/dev/null | grep ":${PORT} " | awk '{print $7}' | cut -d'/' -f1)
        if [ ! -z "$PID" ] && [ "$PID" != "-" ]; then
            echo "发现端口 ${PORT} 被进程 $PID 占用，正在清理..."
            kill -9 $PID 2>/dev/null
            sleep 2
        fi
    fi
}

# 检查进程是否假死
check_health() {
    local pid=$1
    # 检查进程是否响应（通过发送信号0）
    if kill -0 $pid 2>/dev/null; then
        return 0
    else
        echo "进程 $pid 无响应"
        return 1
    fi
}

# 健壮的停止函数
stop() {
    echo "正在停止 JavaBridge..."
    
    # 方法1: 通过端口查找进程
    PORT_PID=$(lsof -ti:${PORT})
    if [ ! -z "$PORT_PID" ]; then
        echo "通过端口找到进程: $PORT_PID"
        kill -TERM $PORT_PID
        sleep 3
    fi
    
    # 方法2: 通过进程名查找
    JAR_PID=$(pgrep -f "java.*JavaBridge.jar")
    if [ ! -z "$JAR_PID" ]; then
        echo "通过进程名找到进程: $JAR_PID"
        kill -TERM $JAR_PID
        sleep 3
    fi
    
    # 强制清理残留进程
    if [ ! -z "$PORT_PID" ] || [ ! -z "$JAR_PID" ]; then
        echo "强制清理残留进程..."
        pkill -9 -f "java.*JavaBridge.jar" 2>/dev/null
        sleep 2
    fi
    
    echo "停止完成"
}

# 增强的启动逻辑
start() {
    echo "启动 JavaBridge..."
    
    # 前置检查
    validate_paths
    check_commands
    check_port
    
    # 检查是否已运行
    JAR_PID=$(pgrep -f "java.*JavaBridge.jar")
    if [ ! -z "$JAR_PID" ]; then
        echo "JavaBridge 已在运行 (PID: $JAR_PID)"
        echo "先停止现有进程..."
        stop
        sleep 2
    fi
    
    # 启动进程 - 直接输出到按天存储的日志文件
    echo "执行命令: ${JAVA_CMD} ${JAVA_OPTS} -jar \"${JAR_PATH}\" ${BRIDGE_OPTS}"
    nohup ${JAVA_CMD} ${JAVA_OPTS} -jar "${JAR_PATH}" ${BRIDGE_OPTS} > "$DAILY_LOG" 2>&1 &
    local pid=$!
    
    echo "JavaBridge 启动中，进程ID: $pid"
    echo "日志文件: $DAILY_LOG"
    
    # 等待进程启动
    sleep 5
    
    # 检查启动状态
    if check_health $pid; then
        echo "JavaBridge 启动成功，进程ID: $pid"
        
        # 检查端口
        if netstat -tlnp 2>/dev/null | grep -q ":${PORT}.*LISTEN"; then
            echo "端口 ${PORT} 正在监听"
        else
            echo "警告: 端口 ${PORT} 未检测到"
        fi
        
        # 显示初始日志
        echo "初始日志输出:"
        tail -10 "$DAILY_LOG"
    else
        echo "JavaBridge 启动失败"
        echo "启动日志:"
        tail -20 "$DAILY_LOG"
        exit 1
    fi
}

# 状态检查函数
status() {
    # 检查进程名
    local pid=$(pgrep -f "java.*JavaBridge.jar")
    if [ ! -z "$pid" ]; then
        echo "JavaBridge 运行中，进程ID: $pid"
        # 检查端口占用
        local port_pid=$(lsof -ti:${PORT})
        if [ ! -z "$port_pid" ]; then
            echo "端口 ${PORT} 被进程 $port_pid 占用"
        else
            echo "端口 ${PORT} 未被占用"
        fi
    else
        echo "JavaBridge 未运行"
    fi
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status
        ;;
    restart)
        echo "重启 JavaBridge..."
        stop
        sleep 3
        start
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac